
const router = require('koa-router')();
const util = require("../common/utils")
const { sequelize } = require('../common/dbs')
let jwt = require('jsonwebtoken');
const euModel = require("../models/email_user")
const userinfo = euModel(sequelize);
var md5 = require('md5-node');

// 生成加盐
function randomCoding(n = 8) {
    //创建26个字母数组
    var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    var idvalue = '';
    for (var i = 0; i < n; i++) {
        idvalue += arr[Math.floor(Math.random() * 26)];
    }
    return idvalue;
}

/**
 * 注册
 * */
router.post('/register', async (ctx) => {
    try {
        ctx
            .validateBody("email")
            .required("邮箱不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("pwd")
            .required("用户密码不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        // 查询账号是否存在
        let cardData = await userinfo.findOne(
            {
                where: {
                    email: reqBody.email
                }
            }
        );
        if (cardData) {
            ctx.body = util.resultError({ code: 0, message: '账号已经存在了', data: null });
            return
        }
        //  生成加盐
        let salt = randomCoding();
        //  生成密码
        //  生成token 默认token
        let id = getuuid()
        let key = getuuid(64)
        let requestData = await userinfo.create({
            _id: id,
            email: reqBody.email,
            key: key,
            pwdSalt: salt,
            pwd: md5(reqBody.pwd + salt),
        })
        if (requestData) {
            let url = `https://www.itliuyang.com/nav/activation?id=${id}&key=${key}`
            util.sendMail('153115598@qq.com', 'itliuyang', reqBody.email,
                '导航站的激活地址',
                `<div class="email-box" style="border: 1px dashed #9db0ef;border-radius: 5px;padding: 20px;    margin: 10px;">
        <div class="content">
            <p class="header">
                <a href="${url}" target="_blank" rel="noopener">
                   点击激活 ${url}
                </a>
            </p>
            <p class="no_indent">
                欢迎您再次光临
                <a href="https://www.itliuyang.com/nav" target="_blank" rel="noopener">
                导航站
                </a>
                ！
            </p>
        </div>
        <div class="footer">
            <p style="color:#2a3e42; text-align: center;">
                Copyright ©
                <span style="border-bottom:1px dashed #ccc;z-index:1" t="7" onclick="return false;" data="2019-2020">
                    2012-2021
                </span>
                <a href="https://www.itliuyang.com/nav" target="_blank" rel="noopener">
                    导航站
                </a>
                - 本邮件由系统自动生成发送，请勿直接回复！
            </p>
        </div>
    </div>`);

            ctx.body = util.resultSuccess({ message: '注册成功,请前往邮箱激活', data: url });
        } else {
            ctx.body = util.resultError({ code: 0, message: '注册失败，请稍后再试', data: null });
        }
    } catch (err) {
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})

// 激活
router.get('/activation', async (ctx) => {
    try {

        let reqQuery = ctx.request.query;
        if (!reqQuery.id || !reqQuery.key) {
            ctx.body = util.resultError({ data: '激活链接失效了' });
            return
        }
        let info = await userinfo.findOne(
            {
                where: {
                    _id: reqQuery.id,
                    key: reqQuery.key
                }
            });
        if (info.isOpen == 1) {
            ctx.body = util.resultError({ data: '已经激活了' });
            return
        }

        let cardData = await userinfo.update(
            { isOpen: 1 }, {
            where: {
                _id: reqQuery.id,
                key: reqQuery.key
            },
        });


        if (cardData[0] > 0) {
            ctx.body = util.resultSuccess({ data: '激活成功，快去登录吧' });
        } else {
            ctx.body = util.resultError({ data: '激活地址错误' });
        }
    } catch (err) {
        ctx.body = util.resultError({ data: err.message });
    }
})


/**
 * 登录
 * */
router.post('/login', async (ctx) => {
    try {
        ctx
            .validateBody("email")
            .required("用户账号不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("pwd")
            .required("用户密码不能为空")
            .isString()
            .trim()



        let reqBody = ctx.request.body;
        // 查询账号是否存在
        let cardData = await userinfo.findOne(
            {
                where: {
                    email: reqBody.email
                }
            }
        );
        if (!cardData) {
            ctx.body = util.resultError({ code: 0, message: '登录失败，该账号不存在', data: null });
            return
        }
        if (cardData.isOpen == 0) {
            ctx.body = util.resultError({ code: 0, message: '登录失败，该账号未激活', data: null });
            return
        }
        // 加盐
        if (md5(reqBody.pwd + cardData.pwdSalt) == cardData.pwd) {
            let payload = {
                "email": md5(cardData.email),
                "id": md5(cardData._id)
            }
            let newToken = jwt.sign(payload, 'itliuyang', { expiresIn: 60000 });
            console.log(newToken);
            let updateInfo = await userinfo.update({
                token: newToken
            }, {
                where: {
                    _id: cardData._id
                }
            })
            if (updateInfo) {
                ctx.body = util.resultSuccess({
                    message: '登录成功', data: {
                        token: newToken
                    }
                });
            } else {
                ctx.body = util.resultError({ code: 0, message: '登录失败，请稍后再试', data: null })
            }

        } else {
            ctx.body = util.resultError({ code: 0, message: '登录失败，账号或者密码错误', data: null });
        }
    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})


// 获取随机id
function getuuid(number = 36) {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < number; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    if (number > 14) {
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    }
    // s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
}
module.exports = router.routes();